package cn.schoolwow.quickdao.module.database.ddl.action.flow.table.common;

import cn.schoolwow.quickdao.domain.QuickDAOConfig;
import cn.schoolwow.quickdao.domain.database.ddl.IndexField;
import cn.schoolwow.quickdao.domain.entity.Entity;
import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;

public class BuildIndexFlow implements BusinessFlow {
    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        StringBuilder sqlBuilder = (StringBuilder) flowContext.checkData("sqlBuilder");
        Entity entity = (Entity) flowContext.checkData("entity");
        QuickDAOConfig quickDAOConfig = flowContext.checkInstanceData(QuickDAOConfig.class);

        for (IndexField indexField : entity.indexFieldList) {
            sqlBuilder.append("create");
            switch (indexField.indexType) {
                case NORMAL: {
                }
                break;
                case UNIQUE: {
                    sqlBuilder.append(" unique");
                }
                break;
                case FULLTEXT: {
                    sqlBuilder.append(" fulltext");
                }
                break;
            }
            if(null==indexField.indexName||indexField.indexName.isEmpty()){
                StringBuilder indexNameBuilder = new StringBuilder(indexField.tableName + "_"+indexField.indexType.name().toLowerCase() + "_");
                for (String column : indexField.columns) {
                    indexNameBuilder.append(column + ",");
                }
                indexNameBuilder.deleteCharAt(indexNameBuilder.length()-1);
                indexField.indexName = indexNameBuilder.toString();
            }
            sqlBuilder.append(" index " + quickDAOConfig.databaseContext.databaseProvider.escape(indexField.indexName) + " on " + quickDAOConfig.databaseContext.databaseProvider.escape(indexField.tableName) + "(");
            for (String column : indexField.columns) {
                sqlBuilder.append(quickDAOConfig.databaseContext.databaseProvider.escape(column) + ",");
            }
            sqlBuilder.deleteCharAt(sqlBuilder.length() - 1);
            sqlBuilder.append(")");
            if (null != indexField.using && !indexField.using.isEmpty()) {
                sqlBuilder.append(" using " + indexField.using);
            }
            if (null != indexField.comment && !indexField.comment.isEmpty()) {
                sqlBuilder.append(" " + quickDAOConfig.databaseContext.databaseProvider.comment(indexField.comment));
            }
            sqlBuilder.append(";");
        }
    }

    @Override
    public String name() {
        return "构建外键关联语句";
    }
}
